package com.example.home.vm

import com.example.common.view.vm.BaseViewModel
import com.example.home.api.HomeApiService
import com.example.home.entity.HomeListEntityItem
import com.example.home.model.HomeRepository
import com.example.home.model.HomeResultData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 协程调度器Dispatchers
 * Dispatchers.IO 在子线程中调度(使用线程池64),适用于耗时多任务场景
 * Dispatchers.Main：在主线程中调度(在UI线程,只有1个),适用于UI更新
 * Dispatchers.Default 取决于调用方(固定数量线程池,其中线程数CPU个数+1),适用于少量任务复杂计算
 * Dispatchers.Unconfined：没有限制(没有限制线程数量)
 **/
@HiltViewModel
class HomeViewModel @Inject constructor(private val apiService: HomeApiService):BaseViewModel<HomeRepository,HomeResultData<List<HomeListEntityItem>>>(){
    fun getListData(page:Int,size:Int){
        mViewModelScope.launch(mDispatcher){
            try {
                val result =apiService.getAnnouncements(page,size)
                val res = HomeResultData(
                    state = result.state,
                    msg = result.msg,
                    data=result.data
                )
                mSuccessLiveData.postValue(res)
            }catch (e:Exception){
                mErrorLiveData.postValue("请求失败:${e.message}")
            }
        }
    }
}